"use client";
import { claimActivityReward, getJackpotInfo, GetJackpotResponse } from "@/api/activity";
import GlobalNotify from "@/components/ModalPopup/GlobalNotifyModal";
import { formatAmount } from "@/utils";
import { Toast } from "antd-mobile";
import BigNumber from "bignumber.js";
import clsx from "clsx";
import dayjs from "dayjs";
import { useTranslations } from "next-intl";
import { useSearchParams } from "next/navigation";
import React from "react";
import styles from "./style.module.scss";

// const tabCftg = React.useMemo(() => {
//     return [
//         {
//             image: "/jackpot/2.png",
//             text: "Dia 2",
//             key: 2,
//         },
//         {
//             image: "/jackpot/3.png",
//             text: "Dia 3",
//             key: 3,
//         },
//         {
//             image: "/jackpot/7.png",
//             text: "Dia 7",
//             key: 7,
//         },
//         {
//             image: "/jackpot/15.png",
//             text: "Dia 15",
//             key: 15,
//         },
//         {
//             image: "/jackpot/30.png",
//             text: "Dia 30",
//             key: 30,
//         },
//     ];
// }, []);

const Jackpot: React.FC = () => {
    const searchParams = useSearchParams();
    const t = useTranslations();
    const [actKey, setActKey] = React.useState<number | string>(2);
    const [infoData, setInfoData] = React.useState<GetJackpotResponse>();
    const activeId = searchParams.get("activity_id");
    const [amount, setAmount] = React.useState<any>({});
    const [visible, setVisible] = React.useState<boolean>(false);

    const images = React.useMemo(() => {
        return [
            "/jackpot/2.png",
            "/jackpot/3.png",
            "/jackpot/7.png",
            "/jackpot/15.png",
            "/jackpot/30.png",
        ];
    }, []);
    const curTabData: any = React.useMemo(() => {
        return infoData?.list[`${actKey}`] || {};
    }, [actKey, infoData]);

    const list = React.useMemo(() => {
        const base = [
            {
                left: "Ãmbito do depósito",
                right: "Bónus Misterioso",
            },
        ];
        if (curTabData?.arr) {
            for (let i = 0; i < curTabData.arr.length; i++) {
                const item = curTabData.arr[i];
                base.push({
                    left: `R$ ${formatAmount(item.min)}-${formatAmount(item.max)}`,
                    right: `R$ ${formatAmount(item.show_min)}-${formatAmount(item.show_max)}`,
                });
            }
        }
        return base;
    }, [curTabData]);
    React.useEffect(() => {
        getInfoData();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    const getInfoData = async () => {
        if (!activeId) return;
        try {
            const res = await getJackpotInfo({ activity_id: Number(activeId) });

            if (res.code === 200) {
                if (res.data.list) {
                    const keys = Object.keys(res.data.list);
                    const result: any = {};
                    let initKey = 0;
                    if (keys.length > 0) {
                        for (let i = 0; i < keys.length; i++) {
                            const curKey = keys[i];
                            const curItem = res.data.list[curKey];
                            if (i === 0) {
                                initKey = Number(curKey);
                            }
                            if (curItem?.is_unlock && !curItem?.is_suss) {
                                initKey = Number(curKey);
                            }
                            let time = null;
                            if (res.data) {
                                time = dayjs(res.data.start_at * 1000)
                                    .add(Number(curKey), "day")
                                    .format("YYYY-MM-DD HH:mm");
                            }
                            result[curKey] = {
                                ...curItem,
                                time,
                            };
                        }
                    }
                    setInfoData({ ...res.data, list: result });
                    setActKey(Number(initKey));
                } else {
                    throw new Error(t(`activity.claimError`));
                }
            } else {
                throw new Error(t(`code.${res.code}`));
            }
        } catch (error: any) {
            if (error) {
                Toast.show({
                    content: error.message || error.toString(),
                    maskClickable: false,
                });
            }
        }
    };

    const doClaim = async () => {
        if (!(curTabData?.is_unlock && !curTabData.is_suss)) return;
        try {
            const res = await claimActivityReward({
                activity_id: Number(activeId),
                id: curTabData.id,
            });
            if (res.code === 200 && res?.data?.code === 1) {
                if (res?.data?.reward) {
                    const amountObj: any = {};
                    res?.data?.reward.forEach((item: any) => {
                        amountObj[`coin_${item.coin_type}`] = formatAmount(item.amount);
                    });
                    res?.data?.reward.forEach((item: any) => {
                        amountObj[`coin_${item.coin_type}`] = formatAmount(
                            new BigNumber(amountObj[`coin_${item.coin_type}`] || 0)
                                .plus(item.amount)
                                .toString()
                        );
                    });
                    setAmount(amountObj);
                }
                setVisible(true);
                getInfoData();
            } else {
                throw new Error(t(`code.400`));
            }
        } catch (error: any) {
            if (error) {
                Toast.show({
                    content: error.message || error.toString(),
                    maskClickable: false,
                });
            }
        }
    };

    return (
        <div className={styles.main}>
            <div className={styles.container}>
                <div className={styles.tab}>
                    {infoData?.list &&
                        Object.keys(infoData?.list).map((key: string | number, idx: number) => {
                            const item = infoData?.list[key];
                            return (
                                <div
                                    className={clsx(styles.tabItem, {
                                        [styles.active]: actKey === Number(key),
                                    })}
                                    key={key}
                                    onClick={() => setActKey(Number(key))}
                                >
                                    <img src={images[idx]} />
                                    <span>Dia {key}</span>
                                </div>
                            );
                        })}
                </div>
                <div className={clsx(styles.intro)}>
                    <div
                        className={clsx(
                            styles.introTop,
                            "flex flex-col items-stretch justify-between p-[.12rem_.15rem] text-[.15rem]"
                        )}
                    >
                        <div className={clsx("flex flex-row justify-between")}>
                            <div className={clsx(styles.name, styles.date)}>Hora de registo:</div>
                            <div>
                                {infoData?.display_start_time
                                    ? dayjs(infoData?.display_start_time * 1000).format(
                                          "YYYY-MM-DD HH:mm"
                                      )
                                    : ""}
                            </div>
                        </div>
                        <div className={clsx("flex flex-row justify-between")}>
                            <div className={clsx(styles.name, styles.coin)}>
                                Depósito total de {actKey} Dias:
                            </div>
                            <div>R$ {formatAmount(infoData?.pay_amount || 0)}</div>
                        </div>
                    </div>
                    <div className={clsx(styles.introBottom, styles.big)}>
                        <div className="text-center">
                            0 momento em que os bonus podem serreclamados:
                        </div>
                        <div
                            className={clsx(
                                styles.date,
                                "relative mt-[.08rem] flex h-[.2rem] w-[1.8rem] flex-row items-center pl-[.3rem] text-[.15rem] font-bold"
                            )}
                        >
                            {curTabData.time}
                        </div>
                        <div
                            className={clsx(
                                styles.coin,
                                "relative mt-[.08rem] flex h-[.2rem] w-[1.8rem] flex-row items-center pl-[.3rem] text-[.15rem] font-bold"
                            )}
                        >
                            Bónus misterioso
                        </div>
                        <div className={clsx("mt-[.08rem] text-[.18rem] font-bold text-[#ffd200]")}>
                            R$ {formatAmount(infoData?.reward || 0)}
                        </div>
                    </div>
                </div>
                <div className={clsx("mt-[.2rem] flex flex-row justify-center")}>
                    <div
                        className={clsx(styles.btn, {
                            [styles.disabled]: !(!curTabData.is_suss && curTabData.is_unlock),
                        })}
                        onClick={doClaim}
                    >
                        <span className={clsx("mt-[.1rem] text-[.2rem] font-[900]")}>RECEBER</span>
                    </div>
                </div>
                <div className={clsx("ml-[.14rem] mr-[.14rem] mt-[.2rem]")}>
                    {list.map((item, index) => {
                        return (
                            <div
                                key={index}
                                className={clsx(
                                    "flex flex-row items-center justify-between",
                                    styles.cfgItem,
                                    {
                                        [styles.odd]: index % 2 === 0,
                                        [styles.title]: index === 0,
                                    }
                                )}
                            >
                                <div className={styles.left}>{item.left}</div>
                                <div className={styles.right}>{item.right}</div>
                            </div>
                        );
                    })}
                </div>
                <div
                    className={clsx("ml-[.18rem] mr-[.18rem] mt-[.3rem] pb-[.3rem] text-[#f7ebff]")}
                >
                    <div className={clsx("mb-[.1rem] font-[700]")}>Descriçäo da Atividade</div>
                    <div className={clsx("mb-[.1rem] text-[.12rem]")}>
                        1.Novos usuários podem participar de prémios misteriosos nosegundo,
                        terceiro, sétimo, décimo quinto e trigésimo dia apóso registro.
                    </div>
                    <div className={clsx("mb-[.1rem] text-[.12rem]")}>
                        2.Quanto mais depÃsitos, maior o tempo online, e maior obÃnus para o evento.
                    </div>
                </div>
            </div>
            <GlobalNotify
                amount={amount}
                visible={visible}
                onChange={() => setVisible(false)}
                deraction={5000}
            ></GlobalNotify>
        </div>
    );
};

export default Jackpot;
